package com.lib.utls.pop;

import android.app.AlertDialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.base.R;
import com.lib.bean.PushDetailBean;
import com.lib.bean.RoomStateBean;
import com.lib.bean.StudentCancelQuestionBean;
import com.lib.bean.ToLiveBean;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.permission.custom.PermissionUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.utils.timer_countdown.CountDownTimer;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.observer.ObserverManager;
import com.lib.utls.glide.GlideConfig;
import com.luck.picture.lib.tools.ToastManage;
import com.zyyoona7.popup.EasyPopup;

public class NewDaYiConnectPopupUtil {

    private Context context;

    public PushDetailBean pushDetailBean;

    public NewDaYiConnectPopupUtil(Context context) {

        this.context = context;

        initPopuPopu();
    }

    private EasyPopup popu;


    private void initPopuPopu() {

        popu = EasyPopup.create()
                .setContext(context)
                .setOutsideTouchable(false)
                .setContentView(R.layout.popup_dayi_connect)
                .setWidth(WindowManager.LayoutParams.FILL_PARENT)
                .setHeight(WindowManager.LayoutParams.FILL_PARENT)
                .setOnViewListener(new EasyPopup.OnViewListener() {
                    @Override
                    public void initViews(View view, EasyPopup basePopup) {

                        initView(view);
                    }

                })
                .setFocusAndOutsideEnable(true)
                .apply();
    }

    private ImageView ivUser;
    private TextView tvName, tvMoney, tvType, tvTime;
    private Button btnCancel, btnSure;


    private void initView(View view) {

        ivUser = view.findViewById(R.id.iv_user);
        tvName = view.findViewById(R.id.tv_name);

        tvTime = view.findViewById(R.id.tv_time);
        tvMoney = view.findViewById(R.id.tv_money);
        btnCancel = view.findViewById(R.id.btn_cancel);
        btnSure = view.findViewById(R.id.btn_sure);

        tvType = view.findViewById(R.id.tv_type);

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //toclass  --------------- pushDetailBean --- username,usericon
                if (pushDetailBean != null) {

                    dismiss();

                    //先判断老师是否已经下课，如果下课了，则隐藏弹出框，并修改平板等待状态
                    if (pushDetailBean.getType() == 7) {
                        judgeConnectRoomIsClosed(pushDetailBean);
                    } else if (pushDetailBean.getType() == 8) {
                        judgeAIStudyRoomIsClosed(pushDetailBean);
                    }

                    //将是否等待数据设置为0，方便外部判断
                    UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(context).getUserCache();
                    userCacheInterface.setIsWait(0);

                }
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (pushDetailBean != null) {

                    if (pushDetailBean.getType() == 8) {

                        //将是否等待数据设置为0，方便外部判断
                        UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(context).getUserCache();
                        userCacheInterface.setIsWait(0);
                    }
                    showTipsDialog("roomStateNormal");

                }
            }
        });

    }

    /**
     * 判断AI辅导房间是否已经关闭
     *
     * @param pushDetailBean
     */
    private void judgeAIStudyRoomIsClosed(final PushDetailBean pushDetailBean) {

        HttpUtils.with(context)
                .addParam("requestType", "AI_WHETHER_THE_TEACHER_HAS_WITHDRAWN")
                .addParam("token", SharedPreferenceManager.getInstance(context).getUserCache().getUserToken())
                .addParam("course_id", pushDetailBean.getObj().getCourse_id())
                .execute(new HttpDialogCallBack<RoomStateBean>() {
                    @Override
                    public void onSuccess(RoomStateBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (result.getObj() != null) {
                                if (result.getObj().getFinish_class() > -1) {
                                    //（0-已退出，1-未退出）
                                    if (0 == result.getObj().getFinish_class()) {

                                        //将是否等待数据设置为0，方便外部判断
                                        UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(context).getUserCache();
                                        userCacheInterface.setIsWait(0);

                                        showTipsDialog("roomTimeOut");

                                    } else if (1 == result.getObj().getFinish_class()) {

                                        goToClass(pushDetailBean);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    /**
     * 判断连麦答疑房间是否已经关闭
     *
     * @param pushDetailBean
     */
    private void judgeConnectRoomIsClosed(final PushDetailBean pushDetailBean) {

        HttpUtils.with(context)
                .addParam("requestType", "WHETHER_THE_TEACHER_HAS_WITHDRAWN")
                .addParam("token", SharedPreferenceManager.getInstance(context).getUserCache().getUserToken())
                .addParam("course_id", pushDetailBean.getObj().getCourse_id())
                .execute(new HttpDialogCallBack<RoomStateBean>() {
                    @Override
                    public void onSuccess(RoomStateBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (result.getObj() != null) {
                                if (result.getObj().getFinish_class() > -1) {
                                    //（0-已退出，1-未退出）
                                    if (0 == result.getObj().getFinish_class()) {

                                        showTipsDialog("roomTimeOut");

                                    } else if (1 == result.getObj().getFinish_class()) {

                                        goToClass(pushDetailBean);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });


    }


    private void showTipsDialog(String connectState) {

        View view = LayoutInflater.from(context).inflate(R.layout.dialog_dayiconnect_refuse, null);

        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvSure = view.findViewById(R.id.tv_sure);
        TextView tvContent = view.findViewById(R.id.tv_content);

        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setView(view)
                .setCancelable(true)
                .show();

        if (pushDetailBean != null) {

            if ("roomStateNormal".equals(connectState)) {
                if (7 == pushDetailBean.getType()) {

                    tvContent.setText("   因老师已开启直播间，如果取消进入，暂压的兔币将不会退还给您，是否确定取消进入并退出？");
                } else if (8 == pushDetailBean.getType()) {

                    tvContent.setText("   因老师已开启直播间，如果取消进入，作业辅导将会扣除 1 次，是否确定取消进入并退出？");
                }
            } else if ("roomTimeOut".equals(connectState)) {

                tvContent.setText("   因您长时间未进入，老师已关闭直播间，请重新提问！");
            }

        }

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //学生取消进入直播间
                sendCancelToRommToSerVice();
                dialog.dismiss();
            }
        });
    }

    /**
     * 发送取消进入直播间到服务器
     * quiz_or_live 0-取消提问,1-取消进入直播间
     */
    private void sendCancelToRommToSerVice() {

        HttpUtils.with(context)
                .addParam("requestType", "STUDENT_CANCEL_QUESTION_AND_ANSWER")
                .addParam("quiz_or_live", 1)
                .addParam("token", SharedPreferenceManager.getInstance(context).getUserCache().getUserToken())
                .execute(new HttpDialogCallBack<StudentCancelQuestionBean>() {
                    @Override
                    public void onSuccess(StudentCancelQuestionBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            ToastManage.s(context, "取消成功");
                            dismiss();

                            //学生取消进入直播间，关闭等待页面
                            ObserverManager.getInstance().notifyObserver("CloseWaitActivity");
                        }
                    }

                    @Override
                    public void onError(String e) {
                        dismiss();
                    }
                });

    }

    private void showData(PushDetailBean pushDetailBean) {

        if (pushDetailBean != null) {

            if (StringUtil.isNotEmpty(pushDetailBean.getObj().getPhoto_url(), true)) {

                Glide.with(context)
                        .load(pushDetailBean.getObj().getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }

            if (StringUtil.isNotEmpty(pushDetailBean.getObj().getTeacher_name(), true)) {
                tvName.setText(pushDetailBean.getObj().getTeacher_name() + "");
            }

            if (StringUtil.isNotEmpty(pushDetailBean.getObj().getExpected_value() + "", true)) {

                if (pushDetailBean.getType() == 7) {
                    tvMoney.setText(pushDetailBean.getObj().getExpected_value() + "兔币");
                } else if (pushDetailBean.getType() == 8) {
                    tvMoney.setText(pushDetailBean.getObj().getExpected_value() + "");
                }
            }

            if (pushDetailBean.getType() == 7) {

                tvType.setText("已接收你的提问");
                tvTime.setText("每3分钟消耗：");
            } else if (pushDetailBean.getType() == 8) {

                tvType.setText("已接受你的作业辅导");
                tvTime.setText("本次辅导消耗次数：");
            }

        }
    }


    public void dismiss() {

        popu.dismiss();
        timer.cancel();
    }

    public void showAnswerPopuPopu(View view) {

        popu.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    public void updateData(PushDetailBean pushDetailBean) {

        if (pushDetailBean != null) {
            this.pushDetailBean = pushDetailBean;
            showData(pushDetailBean);

            //开始进入直播间倒计时，5秒后如果没点就直接进入
            timer.start();
        }

    }

    CountDownTimer timer = new CountDownTimer(5 * 1000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {

            btnSure.setText(millisUntilFinished / 1000 + "秒");
        }

        @Override
        public void onFinish() {

            if (pushDetailBean != null) {

                dismiss();

                //先判断老师是否已经下课，如果下课了，则隐藏弹出框，并修改平板等待状态
                if (pushDetailBean.getType() == 7) {
                    judgeConnectRoomIsClosed(pushDetailBean);
                } else if (pushDetailBean.getType() == 8) {
                    judgeAIStudyRoomIsClosed(pushDetailBean);
                }

                //将是否等待数据设置为0，方便外部判断
                UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(context).getUserCache();
                userCacheInterface.setIsWait(0);
            }
        }
    };

    private void goToClass(final PushDetailBean pushDetailBean) {

        //保存课程的类型以及该课程的Id，用于RoomControlFragment分享
        final UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(context).getUserCache();
        userCacheInterface.setBussessType(pushDetailBean.getObj().getCourse_type() + "");
        userCacheInterface.setCourseId(pushDetailBean.getObj().getCourse_id() + "");

        HttpUtils.with(context)
                .addParam("requestType", "TO_CLASS")
                .addParam("course_type", pushDetailBean.getObj().getCourse_type())
                .addParam("course_id", pushDetailBean.getObj().getCourse_id())
                .addParam("token", SharedPreferenceManager.getInstance(context).getUserCache().getUserToken())
                .execute(new HttpDialogCallBack<ToLiveBean>() {
                    @Override
                    public void onSuccess(ToLiveBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            String roomToken = result.getObj().getRoomtoken();
                            String teacherPhone = result.getObj().getPhoen();

                            LogUtil.e("teacherPhone=" + teacherPhone +
                                    "roomName=" + result.getObj().getRoomname() + "uuid=" + result.getObj().getUuid()
                                    + "roomToken的值为：" + roomToken);

                            if (pushDetailBean != null) {
                                //如果类型为7，代表在线答疑推送，进入相应直播间
                                if (pushDetailBean.getType() == 7) {

                                    ARouter.getInstance().build(ARouterPathUtils.Tablet_Live_LiveRoomActivity)
                                            .withString("roomToken", roomToken)
                                            .withString("teacherPhone", teacherPhone)
                                            .withString("roomName", result.getObj().getRoomname())
                                            .withString("userPhone", SharedPreferenceManager.getInstance(context).getUserCache().getUserPhone())
                                            .withString("uuid", result.getObj().getUuid())
                                            .withString("whitetoken", result.getObj().getWhitetoken())
                                            .withString("teacherHeadUrl", pushDetailBean.getObj().getPhoto_url())
                                            .withString("teacherName", pushDetailBean.getObj().getTeacher_name())
                                            .withInt("studentId", pushDetailBean.getObj().getTeacher_id())
                                            .withInt("teacherId", pushDetailBean.getObj().getStudent_id())
                                            .withString("course_id", pushDetailBean.getObj().getCourse_id() + "")
                                            .navigation();

                                } else if (pushDetailBean.getType() == 8) {

                                    //如果类型为8，代表家庭作业辅导推送，进入相应直播间
                                    ARouter.getInstance().build(ARouterPathUtils.Tablet_CoachStudyLivingActivity)
                                            .withString("roomToken", roomToken)
                                            .withString("teacherPhone", teacherPhone)
                                            .withString("roomName", result.getObj().getRoomname())
                                            .withString("userPhone", SharedPreferenceManager.getInstance(context).getUserCache().getUserPhone())
                                            .withString("uuid", result.getObj().getUuid())
                                            .withString("whitetoken", result.getObj().getWhitetoken())
                                            .withString("course_id", pushDetailBean.getObj().getCourse_id() + "")
                                            .navigation();

                                }

                                ObserverManager.getInstance().notifyObserver("CloseWaitActivity");
                            }

                        } else {

                        }

                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


}
